package com.laxcen.smoke.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laxcen.smoke.dao.RoleDao;
import com.laxcen.smoke.dto.res.RoleListRes;
import com.laxcen.smoke.service.RolesService;
import com.laxcen.smoke.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RolesServiceImpl implements RolesService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public Response insert(String name, String description, int available) {
        roleDao.insert(name,description,available,new Date());
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response update(long id, String name, String description, int available) {
        roleDao.update(name,description,available,new Date(),id);
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response delete(long id) {
        roleDao.delete(id);
        roleDao.deleteRoleAndResource(id);
        roleDao.deleteRoleAndUser(id);
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response deletemore(String id) {
        String[] ids = id.split(",");
        for (int i = 0;i < ids.length;i++){
            roleDao.delete(Long.valueOf(ids[i]));
            roleDao.deleteRoleAndResource(Long.valueOf(ids[i]));
            roleDao.deleteRoleAndUser(Long.valueOf(ids[i]));
        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response<PageInfo<RoleListRes>> get(int pageNo, int pageSize) {
        Page page = PageHelper.startPage(pageNo, pageSize);
        List<RoleListRes> list = roleDao.getRoleList();
        Response<PageInfo<RoleListRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response distribute(long roleid, String resourceid) {
        String[] resourcesid = resourceid.split(",");
        for (int i = 0;i < resourcesid.length;i++) {
            roleDao.insertRoleAndResource(roleid, Long.valueOf(resourcesid[i]), new Date());
        }
        Response response = new Response();
        response.setOK();
        return response;
    }
}
